<template>
  <a-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-align="right"
    :label-col-props="{ span: 6 }"
    :wrapper-col-props="{ span: 18 }"
  >
    <a-form-item field="code" label="设备编号" required>
      <a-input-group>
        <a-input v-model="form.code" placeholder="请输入设备编号" style="width: calc(100% - 100px)" />
        <a-button type="outline" :loading="generating" @click="handleGenerateCode">重新生成</a-button>
      </a-input-group>
    </a-form-item>
    <a-form-item field="name" label="充电桩名称">
      <a-input v-model="form.name" placeholder="请输入充电桩名称" />
    </a-form-item>
    <a-form-item field="socketCount" label="插座数量" required>
      <a-input-number
        v-model="form.socketCount"
        placeholder="请输入插座数量"
        :min="1"
        :max="99"
        style="width: 100%"
      />
    </a-form-item>
    <a-form-item field="chargingGroupId" label="所属站点">
      <a-select
        v-model="form.chargingGroupId"
        placeholder="请选择站点"
        :allow-clear="!props.chargingGroupId"
      >
        <a-option
          v-for="station in stationList"
          :key="station.id"
          :value="station.id"
        >
          {{ station.name }}
        </a-option>
      </a-select>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { getAllCarChargingGroups } from '@/api/car-charging-group';
import { Message } from '@arco-design/web-vue';
import type { FormInstance } from '@arco-design/web-vue';
import type { Result } from '@/types/global';
import request from '@/utils/request';

const props = defineProps<{
  chargingGroupId?: number | null;
  groupName?: string;
  isEdit?: boolean;
  editData?: {
    id?: number;
    code: string;
    name: string;
    socketCount: number;
    chargingGroupId?: number;
  };
}>();

// 监听编辑数据变化
watch(() => props.editData, (newVal) => {
  if (newVal && props.isEdit) {
    setFormData({
      code: newVal.code,
      name: newVal.name,
      socketCount: newVal.socketCount,
      chargingGroupId: newVal.chargingGroupId
    });
  }
}, { immediate: true, deep: true });

const emit = defineEmits(['update:form']);

// 表单引用
const formRef = ref<FormInstance>();

// 站点列表
const stationList = ref<{ id: number; name: string }[]>([]);

// 表单数据
const form = reactive({
  code: '',
  name: '',
  socketCount: 1,
  chargingGroupId: props.chargingGroupId as number | undefined,
});

// 表单校验规则
const rules = {
  code: [{ required: true, message: '请输入设备编号' }],
  socketCount: [{ required: true, message: '请输入插座数量' }],
  chargingGroupId: [{ required: !props.chargingGroupId, message: '请选择站点' }]
};

// 设置表单数据
const setFormData = (data: Partial<typeof form>) => {
  console.log('子组件设置表单数据:', data);
  Object.assign(form, data);
};

// 获取站点列表
async function fetchStationList() {
  try {
    const res = await getAllCarChargingGroups();
    if (res.code === 200 && res.data) {
      stationList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      Message.error(res.message || '获取站点列表失败');
    }
  } catch (error) {
    console.error('获取站点列表失败:', error);
    Message.error('获取站点列表失败');
  }
}

// 表单验证
const validate = () => {
  return formRef.value?.validate();
};

// 获取表单数据
const getFormData = () => {
  console.log('子组件返回表单数据:', form);
  return {
    code: form.code,
    name: form.name,
    socketCount: form.socketCount,
    chargingGroupId: form.chargingGroupId
  };
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  Object.assign(form, {
    code: '',
    name: '',
    socketCount: 1,
    chargingGroupId: props.chargingGroupId as number | undefined,
  });
};

// 生成编号loading状态
const generating = ref(false);

// 生成设备编号
const handleGenerateCode = async () => {
  generating.value = true;
  try {
    // 直接调用接口
    const res = await request.get<Result<string>>('/api/charging/generate-code');
    if (res && res.code === 200 && res.data) {
      form.code = String(res.data); // 确保转换为字符串
      // Message.success('设备编号生成成功');
    } else {
      Message.error((res && res.message) || '设备编号生成失败');
    }
  } catch (error) {
    console.error('生成设备编号失败:', error);
    Message.error('生成设备编号失败');
  } finally {
    generating.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  validate,
  getFormData,
  resetForm,
  setFormData
});

onMounted(() => {
  fetchStationList();
  
  // 如果是新增模式（非编辑模式），则自动生成设备编号
  if (!props.isEdit) {
    handleGenerateCode();
  }
});
</script> 